/*
 * @Author: gk 
 *  机构信息管理
 * @Date: 2018-03-15 14:44:57 
 * @Last Modified by: txy
 * @Last Modified time: 2019-04-26 10:39:39
 */
layui.config({}).use(['element', 'laydate', 'zlConfig', 'zltreemenu','upload', 'zlContext', 'table', 'layer', 'form', 'zlPinYin', 'upload', 'zlSelectEx', 'zlpoptree', 'zlSelecttree'], function (exports) {
	var $ = layui.$,
		zlContext = layui.zlContext,
		zltreemenu = layui.zltreemenu,
		layer = layui.layer,
		table = layui.table,
		form = layui.form,
		zlConfig = layui.zlConfig,
		zlSelecttree = layui.zlSelecttree,
		zlpoptree = layui.zlpoptree,
		statusName = zlConfig.global.result.statusName,
		msgName = zlConfig.global.result.msgName,
		dataName = zlConfig.global.result.dataName,
		OK = zlConfig.global.result.okState,
		fullheight = 'full-30',
		// fullheight = zlContext.setMaxHeihgt(0),
		ERROR = zlConfig.global.result.errorState,
		laydate = layui.laydate,
        isloaded = false,
        upload = layui.upload,
		customCurr = 1;

	form.verify({
		budgetcode: function (value) {
			if (value && /[\u4E00-\u9FA5]/i.test(value)) {
				return '预算代码不能输入中文字符！';
			}
		}
	})
	var treeObj,
		fromlayerIndex,
		currNode,
		tableobj,
        isloadsearch = false,
        data = zlContext.getCurrentUser(),
        isShowAll = data.currentRoleId == 'E555C6219EAD42A69C7DD216528B3F28' ? true : false,
        orgcount;
	var treeAction = {
		loadTree: function () {
			//创建zTree组件
			treeObj = zltreemenu.render('orgTreeId', {
				dataurl: layui.cache['contentPath'] + '/admin/coreorg/queryorgtreelistbyparentid',
				autoParam: ["RWID"],
				tableId: 'tbOrg',
				dataFilter: function (treeId, parentNode, responseData) {
					if (responseData[statusName] == OK) {
                        orgcount= responseData[dataName].length;
                        if (!isloaded && isShowAll) {
							var TopNode = {
								OBJNAME: "机构管理",
								RWID: "",
								SYS_PARENTID: ""
							};
							responseData[dataName].unshift(TopNode);
							isloaded = true;
                        }                       
						return responseData[dataName];
					} else {
						zlContext.errorMsg(responseData[msgName]);
					}
					return responseData;
				}
			}, {
				onClick: function (event, treeId, treeNode) {
					//触发刷新的事件
					if (currNode != treeNode) {
						customCurr = 1;
						customCurr = 1;
						treeAction.raiseResDataEvent(treeNode);
					}
				},
				onAsyncSuccess: function (event, treeId, treeNode, msg) {
					treeObj.selectNode(treeObj.getNodes()[0]);
					treeAction.raiseResDataEvent(treeObj.getNodes()[0]);
				},
				beforeExpand: function (treeId, treeNode) {
					if (treeNode.isParent && treeNode.chield && treeNode.chield.length == 0) {
						treeObj.reAsyncChildNodes(treeNode, "refresh"); //异步刷新，清空后加载，加载后打开,需要不打开加参数true  
						return false;
					} else {
						return true;
					}
				},
				beforeDrop: function (treeId, treeNodes, targetNode, moveType, isCopy) {
					if (treeNodes[0].RWID == '') {
						layer.msg("根节点不能拖动！");
						return false;
					} else if (targetNode == null) {
						return false;
					} else if (targetNode.RWID == '' && (moveType == 'prev' || moveType == 'next')) {
						layer.msg("不能与根节点同级！");
						return false;
					}
				},
				onDrop: function (event, treeId, treeNodes, targetNode, moveType) {
					// 选择一个根节点
					if (moveType == null) {
						return;
					}
					var sourcestreenode = treeNodes[0],
						parentNodeRwid = targetNode.RWID,
						parentsid = sourcestreenode.SYS_PARENTS,
						isleaf = 0,
						data = {};
					if (parentNodeRwid == '') {
						parentsid = parentsid.substr(parentsid.indexOf(sourcestreenode.RWID), parentsid.length);
						if (sourcestreenode.children && sourcestreenode.children.length == 0) {
							isleaf = 1;
						}
					} else {
						parentsid = parentNodeRwid + "_" + parentsid.substr(parentsid.indexOf(sourcestreenode.RWID), parentsid.length);
					}
					data = {
						RWID: sourcestreenode.RWID,
						SYS_PARENTID: parentNodeRwid,
						SYS_PARENTS: parentsid,
						ORGID: sourcestreenode.ORGID,
						SYS_ISLEAF: isleaf
					};
					zlContext.post(layui.cache['contentPath'] + '/admin/coreorg/drag', data, function (result) {
						if (result[statusName] == ERROR) {
							zlContext.errorMsg(result[msgName]);
						} else {
							// treeObj.reAsyncChildNodes(targetNode, "refresh");//异步刷新，清空后加载，加载后打开  
							//由于根节点是手动添加所以不能用 reAsyncChildNodes的方式，否则树会错                         	
							// treeObj.refresh();
							targetNode['isloaded'] = true;
						}
					});
				}
			});
			form.render();
		},
		/**是否能修改 跟节点是不能修改*/
		isRootNode: function () {
			var nodes = treeObj.getSelectedNodes();
			if (nodes.length > 0)
				return nodes[0]['MX_BIANH'] == 'TABLEMODEL';
			return false;
		},
		/**发起刷新明细资料的事件 */
		raiseResDataEvent: function (node) {
			currNode = node;
			if (!node) {
				var nodes = treeObj.getSelectedNodes();
				if (nodes.length > 0)
					currNode = nodes[0];
			}
			$('input[name=type]').val('');
			layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, currNode['RWID']);
		},
		/**新增树节点显示*/
		addChildNode: function (pNode, data) {
			var treeNode = treeObj.addNodes(pNode, data);
			treeObj.selectNode(treeNode[0]);
			treeAction.raiseResDataEvent();
		},
		/**更新树的节点显示 */
		refreshNode: function (node, data) {
			$.each(data, function (k, v) {
				if (node[k]) {
					node[k] = v;
				}
			});
			treeObj.updateNode(node);
			/**刷新页面 */
			treeAction.raiseResDataEvent();
		},
		// 删除节点
		deleteNode: function (treeNode) {
			if (treeNode.length == 0) {
				zlContext.errorMsg('请先选择要删除的机构');
				return;
			}
			if (treeNode[0].children.length == 0) {
				zlContext.deletePost(layui.cache['contentPath'] + '/admin/coreorg/remove', {
						id: treeNode[0].RWID
					},
					function (data) {
						zlContext.successMsg('删除机构成功');
					}
				)
			} else {
				zlContext.warnMsg(treeNode[0]['OBJANME'] + '该机构下还有子机构，请先删除子机构');
			}
		}
	}
	//加载树
	treeAction.loadTree();

	//渲染机构列表
	tableobj = table.render({
		elem: '#tbOrg',
		height: fullheight,
		response: zlConfig.global.gridResponse,
		limit: 20,
		limits: [20, 50, 100, 200, 500, 1000],
		page: true,
		updId: "9C8F43482033482E8C1756264DF2FB0E",
		toolbar: "#toolbarOrg",
		defaultToolbar: ['filter'],
        sortload: true,
        islazyload:true,
		cols: [
			[ //表头
				{
					type: 'numbers',
					fixed: 'left',
					title: '#'
				}, {
					type: 'checkbox',
					fixed: 'left'
				}, {
					field: 'OBJNAME',
					title: '机构名称',
					width: 200,
					sort: true
				}, {
					field: 'OBJCODE',
					title: '代码',
					width: 100,
					sort: true
				}, {
					field: 'JIANC',
					title: '简称',
					width: 200,
					sort: true
				}, {
					field: 'CHENGLRQ',
					title: '成立日期',
					width: 100,
                    sort: true,
                    templet:function(data){
                        if(data.CHENGLRQ){
                            data.CHENGLRQ= data.CHENGLRQ.split(" ")[0];
                            return  data.CHENGLRQ;
                        }else {
                            return ""; 
                        }                        
                        
                    }
				}, {
					field: 'FADDBR',
					title: '法定代表人',
					width: 120,
					sort: true
				}, {
					field: 'DANWLXDH',
					title: '机构联系电话',
					width: 120,
					sort: true
				}, {
					field: 'DANWDZ',
					title: '机构地址',
					width: 200,
					sort: true
				}, {
					field: 'YOUZBM',
					title: '邮政编码',
					width: 100,
					sort: true
				}, {
					field: 'SYS_SORT',
					title: '排序',
					width: 80
				}, {
					fixed: 'right',
					width: 180,
					title: '操作',
					align: 'center',
					toolbar: '#barOrg'
				}
			]
		],
		event: {
			onRowdbClick: function (field, row) {
				gridAction.viewRow(row);
			}
		}
	});
	zlContext.noData($('#tbOrg').siblings('div').find('div.layui-table-main'));

	var gridAction = {
		currentEditObj: undefined,
		orgGridedit: function (orgNode, row, type, readonly) {
			var readonly = readonly && readonly != 0 ? 'disabled' : '';
			var frm = [
				'<div class="site-block layui-fluid" lay-filter="divgridOrg"> <form id ="frmGridOrg" class="layui-form"  action="">'
				, '	<input type="hidden" name="type" lay-verify="required" ' + readonly + ' class="layui-input">'
				, '	<input type="hidden" name="SYS_PARENTID" class="layui-input">'
				, '	<input type="hidden" name="RWID" class="layui-input">'
				, '	<input type="hidden" name="SYS_PARENTS" class="layui-input">'
                , '	<input type="hidden" name="SYS_ISLEAF" class="layui-input">'
                , '	<input type="hidden" name="OLDOBJCODE" class="layui-input">'
				, ' <div class="layui-row" style="padding-top:20px;"> '
				, ' 	<div class="layui-col-md2">&nbsp;</div> '
				, ' 	<div class="layui-col-md8"> '
				, ' 		<div class="danw-xinx"> 基本信息 </div>'
				, ' 		<div class="layui-col-md6"> '
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">机构名称</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text" name="OBJNAME" maxlength="60" lay-verify="required" ' + readonly + ' class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">机构预算码</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text" name="OBJCODE" maxlength="40" lay-verify="required|budgetcode" ' + readonly + ' class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">成立日期</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text" name="CHENGLRQSTR" lay-verify="required" id="CHENGLRQ" ' + readonly + ' readonly="readonly" class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">机构联系电话</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text" name="DANWLXDH" maxlength="13" ' + readonly + ' lay-verify="phone" class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '			</div>'
				, ' 		<div class="layui-col-md6"> '
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">简称</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text" name="JIANC" maxlength="60" lay-verify="required" ' + readonly + ' class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">法定代表人</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text" name="FADDBR" maxlength="20" ' + readonly + ' lay-verify="required|name" class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">排序</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text" name="SYS_SORT" lay-verify="required|number" maxlength="7" placeholder="请输入排序 " ' + readonly + '  class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">邮政编码</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text" name="YOUZBM" maxlength="10" ' + readonly + ' lay-verify="postalCode" class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '			</div>'
				, ' 		<div class="layui-col-md12"> '
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">机构地址</label>'
				, '					<div class="layui-input-block">'
				, '						<textarea name="DANWDZ" maxlength="33" class="layui-textarea" ' + readonly + ' style="min-height:30px;"></textarea>'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">备注</label>'
				, '					<div class="layui-input-block">'
				, '						<textarea name="BEIZ" maxlength="300" class="layui-textarea" ' + readonly + '></textarea>'
				, '					</div>'
				, '				</div>'
				, '			</div>'
				, '		</div>'
				, '	</div>'
				, ' <div class="layui-row" id="asset"> '
				, ' 	<div class="layui-col-md2">&nbsp;</div> '
				, ' 	<div class="layui-col-md8"> '
				, ' 		<div class="danw-xinx"> 资产机构属性 </div>'
				, ' 		<div class="layui-col-md6"> '
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">财政预算代码</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text" name="CAIZYSDM" maxlength="40" ' + readonly + ' class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">组织机构代码</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text" name="ZUZJGDM" maxlength="20"  ' + readonly + ' class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">管理级次</label>'
				, '					<div class="layui-input-block">'
				, '						<select name="GUANLJCID" class="select-ext" zlcomponent ' + readonly + ' lay-filter="GUANLJCID"  settings="{titlefield: \'VALUE\', valuefield: \'DCMX_KEY\',dataurl:\'' + layui.cache['contentPath'] + '/manager/coredictionary/querydictionarybyid?RWID=8E9A8DA8916E4CB6892B88D91803F37E\'}"></select>'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">机构(性质)类型</label>'
				, '					<div class="layui-input-block">'
				, '						<div name="DANWXZLXID" class="layui-form-select select-tree" ' + readonly + ' zlcomponent lay-filter="DANWXZLXID" settings="{name: \'VALUE\', idKey: \'DCMX_KEY\', pIdKey: \'SYS_PARENTID\', rootPid: null, dataurl:\'' + layui.cache['contentPath'] + '/manager/coredictionary/querydictionarybyid?RWID=62DAC5C1F6814B3EA92E22815FBC8589\'}"></div>'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">机构性质类型(ZL)</label>'
				, '					<div class="layui-input-block">'
				, '						<div name="DANWXZLXID_ZL" ' + readonly + ' class="layui-form-select select-tree" zlcomponent lay-filter="DANWXZLXID_ZL" settings="{multselect:false ,id:\'DCMX_KEY\',idKey:\'DCMX_KEY\',pIdKey:\'SYS_PARENTID\',name:\'VALUE\',dataurl:\'' + layui.cache['contentPath'] + '/manager/coredictionary/querydictionarybyid?RWID=62DAC5C1F6814B3EA92E22815FBC8589\'}"></div>'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">机构基本性质</label>'
				, '					<div class="layui-input-block">'
				, '						<div name="DANWJBXZID" class="layui-form-select select-tree" ' + readonly + ' zlcomponent lay-filter="DANWJBXZID" settings="{name: \'VALUE\', idKey: \'DCMX_KEY\', pIdKey: \'SYS_PARENTID\', rootPid: null, dataurl:\'' + layui.cache['contentPath'] + '/manager/coredictionary/querydictionarybyid?RWID=5C43D3FBC9AA421D804872745A19220B\'}"></div>'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">资产管理办法</label>'
				, '					<div class="layui-input-block">'
				, '						<select name="ZICGLBFID" class="select-ext" zlcomponent ' + readonly + '  lay-filter="ZICGLBFID" settings="{titlefield: \'VALUE\', valuefield: \'DCMX_KEY\', dataurl:\'' + layui.cache['contentPath'] + '/manager/coredictionary/querydictionarybyid?RWID=32C1E805C7584169B2C9E69950570735\'}"></select>'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">资产负责人</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text" name="ZICFZR" maxlength="20" ' + readonly + ' class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">批准设立机构</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text" maxlength="33" ' + readonly + ' name="PIZSLDW"  class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '			</div>'
				, ' 		<div class="layui-col-md6"> '
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">机构预算级次</label>'
				, '					<div class="layui-input-block">'
				, '						<select name="DANWYSJCID" class="select-ext" zlcomponent ' + readonly + ' lay-filter="DANWYSJCID"  settings="{titlefield: \'VALUE\', valuefield: \'DCMX_KEY\',dataurl:\'' + layui.cache['contentPath'] + '/manager/coredictionary/querydictionarybyid?RWID=42039E875D314AD79B0F29A2BC010FCB\'}"></select>'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">所属财政关系</label>'
				, '					<div class="layui-input-block">'
				, '						<div name="SUOSCZGXID" zlcomponent class="layui-form-select zlpoptree"  ' + readonly + ' lay-filter="SUOSCZGXID" settings="{ischeckleaf:true,multselect:false,method:\'GET\' ,id:\'DCMX_KEY\',idKey:\'DCMX_KEY\',pIdKey:\'SYS_PARENTID\',name:\'VALUE\',dataurl:\'' + layui.cache['contentPath'] + '/manager/coredictionary/querydictionarybyid?RWID=D0542A829CD3435DA9AB796F146DC373\',formtitle:\'所属财政关系\'}"></div>'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">财务制度</label>'
				, '					<div class="layui-input-block">'
				, '						<select name="CAIWZDID" class="select-ext" zlcomponent ' + readonly + ' lay-filter="DANWJBXZID"  settings="{titlefield: \'VALUE\', valuefield: \'DCMX_KEY\', dataurl:\'' + layui.cache['contentPath'] + '/manager/coredictionary/querydictionarybyid?RWID=171C71D2FFC54A6FA01170A1A27BC700\'}"></select>'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">执行会计制度</label>'
				, '					<div class="layui-input-block">'
				, '						<select name="ZHIXKJZDID" class="select-ext" zlcomponent ' + readonly + ' lay-filter="ZHIXKJZDID"  settings="{titlefield: \'VALUE\', valuefield: \'DCMX_KEY\', dataurl:\'' + layui.cache['contentPath'] + '/manager/coredictionary/querydictionarybyid?RWID=11863A0BEBF9499DA98E92F12C097D0F\'}"></select>'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">资产联系人</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text" name="ZICLXR" maxlength="20" ' + readonly + ' class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">编制人数</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text"  name="BIANZRS" maxlength="5"  ' + readonly + ' class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">批准文号</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text" ' + readonly + ' name="PIZWH" maxlength="33"  class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">行政区划</label>'
				, '					<div class="layui-input-block">'
				, '						<div name="XINGZQHID" class="layui-form-select zlpoptree" ' + readonly + ' zlcomponent lay-filter="XINGZQHID" settings="{ischeckleaf:true,multselect:false,method:\'GET\',id:\'DCMX_KEY\',idKey:\'DCMX_KEY\',pIdKey:\'SYS_PARENTID\',name:\'VALUE\',dataurl:\'' + layui.cache['contentPath'] + '/manager/coredictionary/querydictionarybyid?RWID=317D2C269FBA41BC8946F8F431745ADC\',formtitle:\'选择行政区划\'}"></div>'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">主管部门名称</label>'
				, '					<div class="layui-input-block">'
				, '						<input type="text" name="ZHUGBMMC" maxlength="33"  ' + readonly + ' class="layui-input">'
				, '					</div>'
				, '				</div>'
				, '			</div>'
				, '		</div>'
				, ' 	<div class="layui-col-md2">&nbsp;</div> '
				, '	</div>'
				, ' <div class="layui-row"  id="set"> '
				, ' 	<div class="layui-col-md2">&nbsp;</div> '
				, ' 	<div class="layui-col-md8"> '
				, ' 		<div class="danw-xinx"> 配置项属性 </div>'
				, ' 		<div class="layui-col-md6"> '
				, '	 			<div class="layui-form-item">'
				, '					<label class="layui-form-label">是否启用管理部门</label>'
				, '					<div class="layui-input-block">'
				, '						<select name="SHIFQYGLBM" ' + readonly + ' lay-verify=""><option value=""></option><option value="1">是</option><option value="0">否</option></select>'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">是否启用折旧</label>'
				, '					<div class="layui-input-block">'
				, '						<select name="ISZHEJINIT" ' + readonly + ' lay-verify=""><option value=""></option><option value="1">是</option><option value="0">否</option></select>'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">是否发送邮件</label>'
				, '					<div class="layui-input-block">'
				, '						<select name="ISSENDMAIL" ' + readonly + ' lay-verify=""><option value=""></option><option value="1">是</option><option value="0">否</option></select>'
				, '					</div>'
				, '				</div>'
				, '			</div>'
				, ' 		<div class="layui-col-md6"> '
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">是否开启接口</label>'
				, '					<div class="layui-input-block">'
				, '						<select name="SHIFKQJK" ' + readonly + ' lay-verify=""><option value=""></option><option value="1">是</option><option value="0">否</option></select>'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">是否财政</label>'
				, '					<div class="layui-input-block">'
				, '						<select name="ISCAIZ" ' + readonly + ' lay-verify=""><option value=""></option><option value="1">是</option><option value="0">否</option></select>'
				, '					</div>'
				, '				</div>'
				, '				<div class="layui-form-item">'
				, '					<label class="layui-form-label">是否参公</label>'
				, '					<div class="layui-input-block">'
				, '						<select name="SHIFCZGWYFGL" ' + readonly + ' lay-verify=""><option value=""></option><option value="1">是</option><option value="0">否</option></select>'
				, '					</div>'
				, '				</div>'
				, '			</div>'
				, '		</div>'
				, ' 	<div class="layui-col-md2">&nbsp;</div> '
				, '		</div>'
				, ' <div class="layui-row"> '
				, ' 	<div class="layui-col-md2">&nbsp;</div> '
				, ' 	<div class="layui-col-md8"> '
				, '			<div class="layui-form-item">'
				, '				<div class="layui-input-block">'
				, '				  <button id="btnOrgSaveHidden" class="layui-btn danw-xxbtn" lay-submit lay-filter="frmGridOrg"  ' + readonly + ' data-type="save">保存</button>'
				, '				</div>'
				, '			</div>'
				, '		</div>'
				, '	</div>'
				, '</form></div>'
			];
			layer.open({
				type: 1,
				limit: 999,
				maxmin: true, //最大化按钮
				title: readonly == 'disabled' ? '查看' : (type == 'edit' ? '机构编辑' : '机构新增'),
				id: 'coreorgLayer',
				area: ['100%', '100%'],
				content: frm.join(''),
				success: function (layero, index) {
					laydate.render({
						elem: '#CHENGLRQ', //指定元素
						format: 'yyyy-MM-dd'
                    });
                    if(layui.cache['asset']==0){
                        $('#asset').hide();
                    }
                    if(layui.cache['set']==0){
                        $('#set').hide();
                    }
					if (type == 'detail') { // 查看
						zlContext.autoFill($('#frmGridOrg'), row);
						form.render();
						layero.find('button').hide();
						$('[placeholder]').attr('placeholder', '');
					} else if (type == 'edit') { // 编辑
						zlContext.autoFill($('#frmGridOrg'), row);
						form.render();
                        $('input[name="type"]').val('edit');
                        $('input[name="OLDOBJCODE"]').val(row.OBJCODE);
					} else {                    
						form.render();
						var nodes = treeObj.getSelectedNodes(),
							orgid = '';
						if (nodes.length > 0) {
							orgid = nodes[0]['RWID'];
						}
                        zlContext.autoFill($('#frmGridOrg'), {});
                        if (orgcount) {
                            $('input[name="SYS_SORT"]').val(orgcount + 1);
                        }
						$('input[name="type"]').val('add');
						$('input[name="RWID"]').val('');
						$('input[name="SYS_ISLEAF"]').val('1');
						if (currNode == undefined || currNode == '') {
							$('input[name="SYS_PARENTID"]').val('');
							$('input[name="SYS_PARENTS"]').val('');
						} else {
							$('input[name="SYS_PARENTID"]').val(currNode.RWID);
							$('input[name="SYS_PARENTS"]').val(currNode.SYS_PARENTS);
						}

						if (zlContext.browserType() == 'IE') {
							zlpoptree.render($('div[name=XINGZQHID]'));
							zlpoptree.render($('div[name=SUOSCZGXID]'));
							zlSelecttree.render($('div[name=DANWXZLXID]'));
							zlSelecttree.render($('div[name=DANWXZLXID_ZL]'));
							zlSelecttree.render($('div[name=DANWJBXZID]'));
						}
						//由于layui是主动刷新需要重新刷新才能显示出状态
					}
					fromlayerIndex = index;
				},
				cancel: function (index, layero) {
					if (type == 'edit') {
                        gridAction.currentEditObj.data.OLDOBJCODE = gridAction.currentEditObj.data.OBJCODE;
						zlContext.isFormDataChange('frmGridOrg', gridAction.currentEditObj.data, gridAction, index);
						return false;
					}
				}
			});
		},
		viewRow: function (row) {
			var nodes = treeObj.getSelectedNodes();
			gridAction.orgGridedit(nodes[0], row, 'detail', true);
		},
		newRow: function () {
			var nodes = treeObj.getSelectedNodes(),
				orgid = '';
			if (nodes.length > 0) {
				orgid = nodes[0]['RWID'];
			}
			$('input[name="type"]').val('add');
			$('input[name="RWID"]').val('');
			$('input[name="SYS_ISLEAF"]').val('1');
			if (currNode == undefined || currNode == '') {
				$('input[name="SYS_PARENTID"]').val('');
				$('input[name="SYS_PARENTS"]').val('');
			} else {
				$('input[name="SYS_PARENTID"]').val(currNode.RWID);
				$('input[name="SYS_PARENTS"]').val(currNode.SYS_PARENTS);
			}
			gridAction.orgGridedit(nodes[0], null, 'add');
		},
		editRow: function (row) {
			var nodes = treeObj.getSelectedNodes()
			$('input[name="type"]').val('edit');
			$('input[name="RWID"]').val(nodes[0].RWID);
			gridAction.orgGridedit(nodes[0], row, 'edit');
		},
		deleteRows: function (data, rows) {
			if (rows && rows.length == 0) {
				zlContext.warnMsg('请选择需要删除的机构');
				return;
			}
			var cancontinue = true;
			for (var i = 0; i < rows.length; i++) {
				if (rows[i].RWID == '9C876276D8884BFF94DF343E2A4EED7D') {
					zlContext.errorMsg('选择的记录中包含有通用机构不能一起删除!');
					cancontinue = false;
					return;
				}
			}
			if (!cancontinue) {
				return;
			}
			zlContext.confirm('询问', '是否要删除选择机构?', function (index) {
				ids = [];
				rows.forEach(function (v) {
					ids.push(v.data ? v.data['RWID'] : v['RWID']);
				});
				//提交删除
				zlContext.deletePost(layui.cache['contentPath'] + '/admin/coreorg/remove', {
					ids: ids
				}, function (result) {
					if (result[statusName] == OK) {
                        if (orgcount) {
                            orgcount = orgcount - rows.length;
                        }
						if (rows[0].del) {
                            rows[0].del();
                            if (currNode && currNode.RWID == rows[0].data.RWID) {
                                if (currNode.getParentNode()) {
                                    currNode = currNode.getParentNode();
                                    treeObj.selectNode(currNode);
                                    treeAction.raiseResDataEvent(currNode);
                                } 
                            }
							treeObj.removeNode(treeObj.getNodeByParam("RWID", rows[0].data.RWID, null));
						} else {
							gridAction.refreshGrid('del', null);
							for (var i = 0; i < rows.length; i++) {
                                if (currNode && currNode.RWID == rows[i].RWID) {
                                    if (currNode.getParentNode()) {
                                        currNode = currNode.getParentNode();
                                        treeObj.selectNode(currNode);
                                        treeAction.raiseResDataEvent(currNode);
                                    } 
                                }
								treeObj.removeNode(treeObj.getNodeByParam("RWID", rows[i].RWID, null))
							}
                        }
                       
						// var $pageBox = $('#tbOrg').siblings('div.layui-table-view').find('span.layui-laypage-count'),
						// 	currCount = $pageBox.html().replace(/[^0-9]/ig, ""),
						// 	afterDelNum = parseInt(currCount) - rows.length + '';
						// $pageBox.html('共 ' + afterDelNum + ' 条');
						zlContext.successMsg('删除成功');
					} else {
						zlContext.errorMsg(result[msgName]);
					}
				});
				layer.close(index);
			});
		},
		sumbit: function (fields) {
			var editType = $('#frmGridOrg input[name=type]').val();
			if (editType == 'add') {
				zlContext.put(layui.cache['contentPath'] + '/admin/coreorg/add', fields, function (result) {
					if (result[statusName] == OK) {
                        if (orgcount) {
                            orgcount = orgcount + 1;
                        } else {
                            orgcount = 1;
                        }
                        
						if (currNode != undefined) {
							currNode.SYS_ISLEAF = '0';
							treeObj.updateNode(currNode);
						}
						var newnode = treeObj.addNodes(currNode, 0, result[dataName]);
						treeObj.selectNode(newnode[0]);
						currNode = newnode[0];
						layer.close(fromlayerIndex);
						$('#frmGridOrg input[name=type]').val('');
						gridAction.refreshGrid(editType, result[dataName]);
						zlContext.successMsg('保存成功');
						return true;
					} else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			}
			if (editType == 'edit') {
				zlContext.post(layui.cache['contentPath'] + '/admin/coreorg/modify', fields, function (result) {
					if (result[statusName] == OK) {
						layer.close(fromlayerIndex);
						$('#frmGridOrg input[name=type]').val('');
						fields.CHENGLRQ = fields.CHENGLRQSTR;
						gridAction.refreshGrid(editType, fields);
						zlContext.successMsg('保存成功');
						var nodes = treeObj.transformToArray(treeObj.getNodes());
						if (!nodes) {
							return true;
						}
						for (var i = 0; i < nodes.length; i++) {
							if (nodes[i].RWID == fields.RWID) {
								nodes[i].OBJNAME = fields.OBJNAME
								treeObj.updateNode(nodes[i]);
								break;
							}
						}
						return true;
					} else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			}
			return false;
		},
		search: function () {
			var nodes = treeObj.getSelectedNodes();
			if (nodes.length > 0) {
				customCurr = 1;
				layui.event('WM_USERDEF',
					zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, nodes[0].RWID);
			}
		},
		refreshGrid: function (type, row) {
			/**刷新行 */
			if (type == 'edit' && gridAction.currentEditObj) {
				gridAction.currentEditObj.update(row);
			} else if (type == 'add') {
				//获取选中节点刷新表格
				treeAction.raiseResDataEvent();
			} else if (type == 'del') {
				table.deleteCheckRows('tbOrg');
			}
			form.render();
		}
	}

	// $('#btnSeacher').on('click', function () {
	// 	customCurr = 1;
	// 	gridAction.search();
	// });
	$('.zl-container').on('keyup','#edtSeacherValue', function (event) {
		var keyCode = event.keyCode
			customCurr = 1;
		$('.zl-container').attr('data-search',$(this).val())
		if (keyCode == 13) {
			gridAction.search();
		}
		if ((keyCode == '46' || keyCode == '8' || (event.ctrlKey && keyCode == '86')) && $(this).val() == '' && isloadsearch) {
			$('#btnSeacher').trigger('click');
			isloadsearch = false;
		}
	});

	//头工具栏事件
	table.on('toolbar(tbOrg)', function(obj){
		var checkStatus = table.checkStatus(obj.config.id);
		switch(obj.event){
			case 'btnSeacher':
				customCurr = 1;
				gridAction.search();
				break;
			case 'addOrg':
				gridAction.newRow();
				break;
			case 'deleteOrg':
				var rows = checkStatus.data;
				gridAction.deleteRows(treeObj.getSelectedNodes(), rows);
                break;
            case 'outportmodel':
                location.href=layui.cache['contentPath']+'/static/appdata/filesres/excelTemplate/BdOrgImportModel.xls';
            break; 
		};
	});
	//监听行工具事件
	table.on('tool(tbOrg)', function (obj) {
		var row = obj.data; //获得当前行数据
		var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
		if (layEvent === 'detail') { //查看
			gridAction.viewRow(row);
		} else if (layEvent === 'del') { //删除
			gridAction.currentEditObj = obj;
			gridAction.deleteRows(treeObj.getSelectedNodes(), [obj]);
		} else if (layEvent === 'edit') { //编辑
			gridAction.currentEditObj = obj;
			gridAction.editRow(row);
		}
	});

	//提交
	form.on('submit(frmGridOrg)', function (frm) {
		if ($(frm.elem).hasClass('getField')) {
			gridAction.newFields = frm.field;
			return false;
		}
		return gridAction.sumbit(frm.field);
	});

	//监听刷新的事件
	layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (param) {
		var index = layer.msg('数据查询中，请稍候...', {
			icon: 16,
			time: false,
			shade: 0.1
		});
		var loadGridData = function (id, url, param) {
			tableobj.reload({
				url: url,
				method: 'post',
				// page: {
				// 	curr: customCurr
				// },
				where: param,
				page: {
					curr: customCurr
				},
				done: function (res, curr, count) {
					$('#edtSeacherValue').val($('.zl-container').attr('data-search'))
					layer.close(index);
                    customCurr = curr;
                    var uploadInst = upload.render({
                        elem: '#btnImport',
                        accept: 'file', //所有的文件
                        url: layui.cache['contentPath'] + '/core/excel/excelin',
                        done: function (res) {
                            if (res[statusName] != OK) {
                                // $('#imgPrieviewPic').attr('src', '');
                                return zlContext.errorMsg('导入失败' + res[msgName]);
                            } else {
                                zlContext.successMsg('导入成功');
                                isloaded = false;
                                treeAction.loadTree();
                            }
                        },
                        error: function () {
                            zlContext.errorMsg('上传失败');
                        }
                    });
				}
			}, true);
		}
		// 少一步参数，需要传什么参
		var params = {};
		if ($('#edtSeacherValue').val() !== '') {
			params['OBJNAME'] = $('#edtSeacherValue').val();
			isloadsearch = true;
		}
		if (param) {
			params['RWID'] = param;
		}
		loadGridData('frmGridOrg', layui.cache['contentPath'] + '/admin/coreorg/querydetail', params);
    });


    
	//控制高度
	//iframe自适应
	$(window).on('resize', function () {
		zlContext.setMaxHeihgt(0);
	}).resize();

});